package main

import (
	"fgo/advance/grpc/grpc-gateway/hello-http-ca-tls/tools"
	pb "fgo/advance/grpc/grpc-gateway/proto/hello"
	"fmt"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/grpclog"
	"google.golang.org/grpc/status"
	"time"
)

const (
	// Address gRPC服务地址
	Address = "127.0.0.1:50052"
)

func main() {
	// TLS连接
	tlsClient := tools.Client{
		ServerName: "localhost", // ssl: Common Name (eg, fully qualified host name) []
		CaFile:     "../../keys-ca/ca.pem",
		CertFile:   "../../keys-ca/client.pem",
		KeyFile:    "../../keys-ca/client.key",
	}

	c, err := tlsClient.GetCredentialsByCA()
	if err != nil {
		grpclog.Fatalf("GetTLSCredentialsByCA err: %v", err)
	}

	conn, err := grpc.Dial(Address, grpc.WithTransportCredentials(c))
	if err != nil {
		grpclog.Fatalf("grpc.Dial err: %v", err)
	}
	defer conn.Close()

	ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Duration(5*time.Second)))
	defer cancel()

	// 初始化客户端
	client := pb.NewHelloClient(conn)

	// 调用方法
	resp, err := client.SayHello(ctx, &pb.HelloRequest{
		Name: "gRPC",
	})

	if err != nil {
		statusErr, ok := status.FromError(err)
		if ok {
			if statusErr.Code() == codes.DeadlineExceeded {
				grpclog.Fatalln("client.Search err: deadline")
			}
		}
		grpclog.Fatalf("client.Search err: %v", err)
	}
	fmt.Println(resp.Message)
}
